package cn.factorybox.item.config;

import cn.factorybox.common.entity.Constant;
import cn.factorybox.common.utils.CodecUtils;
import cn.factorybox.common.utils.UUIDUtil;
import cn.factorybox.item.mapper.FactoryDeviceMapper;
import cn.factorybox.item.mapper.RoomMapper;
import cn.factorybox.item.mapper.UserMapper;
import cn.factorybox.model.entity.FactoryDevice;
import cn.factorybox.model.entity.Room;
import cn.factorybox.model.entity.User;
import cn.factorybox.model.entity.UserUpdate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author flypig
 * @version 1.0
 * @date 2020-03-30 18:51
 */
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FactoryDeviceMapper factoryDeviceMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    private final static Logger log = LoggerFactory.getLogger(ApplicationRunnerImpl.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        String[] sourceArgs = args.getSourceArgs();
//        for (String arg : sourceArgs) {
//            System.out.print(arg + " ");
//        }
        // 判断数据库中是否存在管理员用户，没有则创建默认用户
        int userCounts = userMapper.selectAdminUserCount();
        // 先清空redis
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);     // 需要重新定义key的序列化方式，否则无法删除
        // 进行设备数据的缓存，将所有设备号缓存到redis
        List<FactoryDevice> daviceList = factoryDeviceMapper.selectAllDevicesForRedisCache();
        daviceList.forEach(factoryDevice -> {
            redisTemplate.opsForList().rightPush("roomId:" + factoryDevice.getRoomId(),factoryDevice.getValue());
        });
        // 进行房间数据的缓存，将所有房间编号缓存到redis
        List<Room> roomList = roomMapper.selectAllRoomsForRedisCache();
        roomList.forEach(room -> {
            redisTemplate.opsForList().rightPush("companyId:" + room.getCompanyId(),room.getNumber());
        });
        if (userCounts == 0) {
            log.info("项目初始化，创建默认用户");
            User user = new User();
            user.setId(UUIDUtil.uuid());
            user.setuName("admin");
            String salt = CodecUtils.generateSalt();
            user.setSalt(salt);
            user.setuPass(CodecUtils.md5Hex(Constant.USER_INITIAL_PASSWORD,salt));
            user.setRoles("manager");
            user.setuHeadpath("01");
            user.setuRemark("系统超级管理员");
            user.setuCreateTime(new Date());
            this.userMapper.insertUser(user);
            log.info("项目初始化成功");
        } else {
            log.info("项目启动成功");
        }
    }
}
